<?php

class SongLogic {

  function changeState ($id, $state)
  {
  	 $songDao = new SongDAO();

  	 $song = $songDao->get($id);

  	 if ($song != null)
  	 {
	  	 $song->active = $state;

	  	 $songDao->save($song);

	  	 return true;
  	 }
  	 else
  	 {
  	 	return false;
  	 }
  }

  function save(&$song) {
  	$songDao = new SongDAO();

  	return $songDao->save($song) == 1;
  }

  function load($id) {

  	$songDao = new SongDAO();

  	return $songDao->get($id);
  }

  function delete($id) {

	$songDao = new SongDAO();

	return $songDao->delete(new Song($id));
  }

  function findAll($orderBy="") {
     $songDao = new SongDAO();

     return $songDao->findWhere("", $orderBy);
  }

  function activate($id)
  {
  	 self::changeState($id, "T");
  }

  function deactivate($id)
  {
  	self::changeState($id, "F");
  }

  function getInfoPage ($id)
  {
  	$song = self::load($id);

  	return $song->info;
  }

  function getSongDir()
  {
  	// TODO make configurable
  	global $uploadDir;
	if ($uploadDir != "")
	{
		if (!file_exists($uploadDir))
		{
			mkdir($uploadDir);
		}
		return $uploadDir;
	}
	else
	{
  		return ini_get("upload_tmp_dir");
	}
  }

  function getUploadedSong($param)
  {
  	if (isset($_FILES) && isset($_FILES[$param]))
  	{
	  	$uploadDir = self::getSongDir();
	  	$filename = basename($_FILES[$param]['name']);
	  	$filename = str_replace(" ", "_", $filename);
	  	$filename = str_replace("'", "", $filename);
	  	$filename = str_replace("\\", "", $filename);
	  	$uploadfile = $uploadDir . $filename;
		$tmpFile = $_FILES[$param]['tmp_name'];
	  	if (move_uploaded_file($tmpFile, $uploadfile)) {
		   return $filename;
		}
  	}
	return "";
  }

  function removeAudio($id)
  {
  	 $song = self::load($id);
  	 $songDir = self::getSongDir();

  	 if (strlen($song->audio) > 0)
  	 {
  	 	if (unlink($songDir . $song->audio))
  	 	{
  	 		$song->audio = "";
  	 		self::save($song);
  	 	}
  	 }
  }


  function findByAuthor ($author){
  	$songDao = new SongDAO();

  	return $songDao->findWhere("author like '%$author%'");
  }

  function findByTitle ($title){
  	$songDao = new SongDAO();

  	return $songDao->findWhere("title like '%$title%'");
  }

  function findByKey ($key){
  	$songDao = new SongDAO();

  	return $songDao->findWhere("key_played = '$key'");
  }

  function findActive ()
  {
  	$songDao = new SongDAO();

  	return $songDao->findWhere("active = 'T'");
  }

  function findInactive ()
  {
  	$songDao = new SongDAO();

  	return $songDao->findWhere("active = 'F'");
  }

  function findByExample ($song, $order="")
  {
  	 $songDao = new SongDAO();

  	 return $songDao->findExample($song, $order);
  }


}

?>
